package com.tensquare.usercrawler.pipeline;

import com.tensquare.usercrawler.dao.UserDao;
import com.tensquare.usercrawler.pojo.User;
import com.tensquare.usercrawler.util.DownloadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import util.IdWorker;

import java.io.IOException;

/**
 * 用户入库类
 */
@Component
public class UserDbPipeline implements Pipeline{
    @Autowired
    private UserDao userDao;

    @Autowired
    private IdWorker idWorker;

    @Value("${avartar.savePath}")
    private String savePath;

    @Override
    public void process(ResultItems resultItems, Task task) {
        //1.从PageProcessor获取内容
        String nickname = (String)resultItems.get("nickname");
        String avartar = (String)resultItems.get("avartar");

        //2.把用户数据保存到mysql
        User user = new User();
        user.setId(idWorker.nextId()+"");
        user.setNickname(nickname);

        //存储头像地址
        String newAvartar = avartar.substring(avartar.lastIndexOf("/")+1);
        user.setAvatar(newAvartar);
        userDao.save(user);

        //把头像下载到本地
        try {
            DownloadUtil.download(avartar,newAvartar,savePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
